package com.tianji.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.cache.CategoryCache;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.client.search.SearchClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.QuestionFormDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.QuestionAdminPageQuery;
import com.tianji.learning.domain.query.QuestionPageQuery;
import com.tianji.learning.domain.vo.QuestionAdminVO;
import com.tianji.learning.domain.vo.QuestionVO;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动提问的问题表 服务实现类
 * </p>

 * @since 2023-11-06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion> implements IInteractionQuestionService {
    private final InteractionReplyMapper replyMapper;
    private final UserClient userClient;
    private final SearchClient searchClient;
    private final CategoryCache categoryCache;
    private final CatalogueClient catalogueClient;
    private final CourseClient courseClient;


    /**
     * 新增互动问题
     *
     * @param questionDTO
     */
    @Override
    public void saveQuestion(QuestionFormDTO questionDTO) {
        //1、数据拷贝
        InteractionQuestion question = BeanUtils.copyBean(questionDTO, InteractionQuestion.class);
        //2、设置用户ID
        question.setUserId(UserContext.getUser());
        //3、保存数据
        save(question);
    }

    /**
     * 用户端分页查询互动问题
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<QuestionVO> queryQuestionPage(QuestionPageQuery query) {
        //1、参数校验：课程ID和小节ID不能同时为空
        Long courseId = query.getCourseId();
        Long sectionId = query.getSectionId();
        if (ObjectUtil.isEmpty(courseId) && ObjectUtil.isEmpty(sectionId)) {
            throw new BadRequestException("课程ID和小节ID不能同时为空");
        }

        //2、分页查询
        //select * from interaction_question where
        //    user_id = #{} and course_id = #{} and section_id = #{} and hidden = 0 order by create_time desc limit 0,10
        Page<InteractionQuestion> page = lambdaQuery()
                .select(InteractionQuestion.class, column -> !column.getProperty().equals("description"))   //排除查询某个字段
                .eq(query.getOnlyMine(), InteractionQuestion::getUserId, UserContext.getUser())
                .eq(ObjectUtil.isNotEmpty(courseId), InteractionQuestion::getCourseId, courseId)
                .eq(ObjectUtil.isNotEmpty(sectionId), InteractionQuestion::getSectionId, sectionId)
                .eq(InteractionQuestion::getHidden, false)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());

        List<InteractionQuestion> records = page.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return PageDTO.empty(page);
        }

        //3、根据用户ID查询提问者信息，根据最近一次回答ID查询最近一次回答信息
        //3.1、从分页查询结果中得到 提问者ID集合、最近一次回答的ID集合
        Set<Long> userIds = new HashSet<>();
        Set<Long> answerIds = new HashSet<>();
        for (InteractionQuestion record : records) {
            answerIds.add(record.getLatestAnswerId());
            if (!record.getAnonymity()) {
                userIds.add(record.getUserId());
            }
        }

        //3.2、根据最近一次回答ID集合进行查询 --> 转成Map （最近一次回答ID：回复对象本身）
        Map<Long, InteractionReply> replyMap = new HashMap<>(answerIds.size());
        if (ObjectUtil.isNotEmpty(answerIds)) {
            List<InteractionReply> replies = replyMapper.selectBatchIds(answerIds);
            for (InteractionReply reply : replies) {
                replyMap.put(reply.getId(), reply);
                if (!reply.getAnonymity()) {
                    userIds.add(reply.getUserId());
                }
            }
        }

        //3.3、根据用户ID集合进行查询 --> 转成Map（用户ID：用户对象本身）
        Map<Long, UserDTO> userMap = new HashMap<>(userIds.size());
        if (ObjectUtil.isNotEmpty(userIds)) {
            List<UserDTO> users = userClient.queryUserByIds(userIds);
            userMap = users.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
        }

        //4、封装VO
        List<QuestionVO> voList = new ArrayList<>(records.size());
        for (InteractionQuestion record : records) {
            //4.1、拷贝属性
            QuestionVO vo = BeanUtils.copyBean(record, QuestionVO.class);

            //4.2、封装提问者信息(提问者昵称、提问者头像)
            if (!record.getAnonymity()) {
                UserDTO userDTO = userMap.get(record.getUserId());
                if (ObjectUtil.isNotEmpty(userDTO)) {
                    vo.setUserName(userDTO.getName());
                    vo.setUserIcon(userDTO.getIcon());
                }
            }

            //4.3、封装最近一次回答的信息（最近一次回答内容、最近回答者昵称）
            InteractionReply reply = replyMap.get(record.getLatestAnswerId());
            if (ObjectUtil.isNotEmpty(reply)) {
                vo.setLatestReplyContent(reply.getContent());
                if (!reply.getAnonymity()) {
                    UserDTO userDTO = userMap.get(reply.getUserId());
                    if (ObjectUtil.isNotEmpty(userDTO)) {
                        vo.setLatestReplyUser(userDTO.getName());
                    }
                }
            }

            voList.add(vo);
        }

        //5、封装DTO，返回DTO
        return PageDTO.of(page, voList);
    }

    /**
     * 用户端根据ID查询互动问题
     *
     * @param id
     * @return
     */
    @Override
    public QuestionVO queryQuestionById(Long id) {
        //1、根据ID查询问题数据
        InteractionQuestion question = this.getById(id);
        //2、数据校验
        if (ObjectUtil.isEmpty(question) || question.getHidden()) {
            return null;
        }
        //3、查询提问者的用户信息
        UserDTO user = null;
        if (!question.getAnonymity()) {
            user = userClient.queryUserById(question.getUserId());
        }
        //4、封装Vo返回
        QuestionVO questionVO = BeanUtils.copyBean(question, QuestionVO.class);
        if (ObjectUtil.isNotEmpty(user)) {
            questionVO.setUserName(user.getName());
            questionVO.setUserIcon(user.getIcon());
        }
        return questionVO;
    }

    /**
     * 管理端分页查询互动问题
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<QuestionAdminVO> queryQuestionPageAdmin(QuestionAdminPageQuery query) {
        //1、调用ES处理课程名称，得到课程ID集合
        List<Long> courseIds = null;
        if (ObjectUtil.isNotEmpty(query.getCourseName())) {
            courseIds = searchClient.queryCoursesIdByName(query.getCourseName());
            if (ObjectUtil.isEmpty(courseIds)) {
                return PageDTO.empty(0L, 0L);
            }
        }

        //2、分页查询问题表
        Integer status = query.getStatus();
        LocalDateTime begin = query.getBeginTime();
        LocalDateTime end = query.getEndTime();
        Page<InteractionQuestion> page = lambdaQuery()
                .in(ObjectUtil.isNotEmpty(courseIds), InteractionQuestion::getCourseId, courseIds)
                .eq(ObjectUtil.isNotEmpty(status), InteractionQuestion::getStatus, status)
                .ge(ObjectUtil.isNotEmpty(begin), InteractionQuestion::getCreateTime, begin)
                .le(ObjectUtil.isNotEmpty(end), InteractionQuestion::getCreateTime, end)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = page.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return PageDTO.empty(page);
        }

        //3、准备VO需要的额外数据：章节数据、课程数据、用户数据
        Set<Long> userIds = new HashSet<>();
        Set<Long> cIds = new HashSet<>();
        Set<Long> cataIds = new HashSet<>();

        //3.1、获取各种数据的ID集合
        for (InteractionQuestion record : records) {
            userIds.add(record.getUserId());  //用户ID
            cIds.add(record.getCourseId());   //课程ID
            cataIds.add(record.getChapterId());   //章ID
            cataIds.add(record.getSectionId());   //小节ID
        }

        //3.2、根据用户ID集合查询用户集合
        List<UserDTO> users = userClient.queryUserByIds(userIds);
        Map<Long, String> userMap = new HashMap<>(users.size());
        if (ObjectUtil.isNotEmpty(users)) {
            userMap = users.stream().collect(Collectors.toMap(UserDTO::getId, UserDTO::getName));
        }

        //3.3、根据课程ID集合查询课程集合
        List<CourseSimpleInfoDTO> cInfos = courseClient.getSimpleInfoList(cIds);
        Map<Long, CourseSimpleInfoDTO> cInfoMap = new HashMap<>(cInfos.size());
        if (ObjectUtil.isNotEmpty(cInfos)) {
            cInfoMap = cInfos.stream().collect(Collectors.toMap(CourseSimpleInfoDTO::getId, Function.identity()));
        }

        //3.4、根据章节ID结合查询章节结合
        List<CataSimpleInfoDTO> catas = catalogueClient.batchQueryCatalogue(cataIds);
        Map<Long, String> cataMap = new HashMap<>(catas.size());
        if (ObjectUtil.isNotEmpty(catas)) {
            cataMap = catas.stream().collect(Collectors.toMap(CataSimpleInfoDTO::getId, CataSimpleInfoDTO::getName));
        }

        //4、封装VO
        List<QuestionAdminVO> voList = new ArrayList<>(records.size());
        for (InteractionQuestion record : records) {
            //4.1、属性拷贝
            QuestionAdminVO vo = BeanUtils.copyBean(record, QuestionAdminVO.class);

            //4.2、设置用户昵称
            vo.setUserName(userMap.getOrDefault(record.getUserId(), ""));

            //4.3、设置课程名称及分类信息
            CourseSimpleInfoDTO courseInfo = cInfoMap.get(record.getCourseId());
            if (ObjectUtil.isNotEmpty(courseInfo)) {
                vo.setCourseName(courseInfo.getName());
                vo.setCategoryName(categoryCache.getCategoryNames(courseInfo.getCategoryIds()));
            }

            //4.4、设置章 和 节名称
            vo.setChapterName(cataMap.getOrDefault(record.getChapterId(), ""));
            vo.setSectionName(cataMap.getOrDefault(record.getSectionId(), ""));

            //4.5、设置回答数
            vo.setAnswerAmounts(record.getAnswerTimes());
            voList.add(vo);
        }

        //5、封装DTO并返回
        return PageDTO.of(page, voList);
    }

    /**
     * 根据ID删除互动问题
     *
     * @param id
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.查询当前问题
        InteractionQuestion q = getById(id);
        if (q == null) {
            return;
        }
        // 3.判断是否是当前用户的问题
        if (!q.getUserId().equals(userId)) {
            // 不是，抛出异常
            throw new BadRequestException("无权删除他人的问题");
        }
        // 4.删除问题
        removeById(id);
        // 5.删除回答
        replyMapper.delete(
                new QueryWrapper<InteractionReply>().lambda().eq(InteractionReply::getQuestionId, id)
        );
    }

    /**
     * 根据ID修改互动问题
     *
     * @param id
     * @param questionDTO
     */
    @Override
    public void updateQuestion(Long id, QuestionFormDTO questionDTO) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.查询当前问题
        InteractionQuestion q = getById(id);
        if (q == null) {
            throw new BadRequestException("问题不存在");
        }
        // 3.判断是否是当前用户的问题
        if (!q.getUserId().equals(userId)) {
            // 不是，抛出异常
            throw new BadRequestException("无权修改他人的问题");
        }
        // 4.修改问题
        InteractionQuestion question = BeanUtils.toBean(questionDTO, InteractionQuestion.class);
        question.setId(id);
        updateById(question);
    }

    /**
     * 管理端根据ID查询互动问题
     *
     * @param id
     * @return
     */
    @Override
    public QuestionAdminVO queryQuestionByIdAdmin(Long id) {
        // 1.根据id查询问题
        InteractionQuestion question = getById(id);
        if (question == null) {
            return null;
        }
        // 2.转PO为VO
        QuestionAdminVO vo = BeanUtils.copyBean(question, QuestionAdminVO.class);
        // 3.查询提问者信息
        UserDTO user = userClient.queryUserById(question.getUserId());
        if (user != null) {
            vo.setUserName(user.getName());
            vo.setUserIcon(user.getIcon());
        }
        // 4.查询课程信息
        CourseFullInfoDTO cInfo = courseClient.getCourseInfoById(
                question.getCourseId(), false, true);
        if (cInfo != null) {
            // 4.1.课程名称信息
            vo.setCourseName(cInfo.getName());
            // 4.2.分类信息
            vo.setCategoryName(categoryCache.getCategoryNames(cInfo.getCategoryIds()));
            // 4.3.教师信息
            List<Long> teacherIds = cInfo.getTeacherIds();
            List<UserDTO> teachers = userClient.queryUserByIds(teacherIds);
            if (CollUtils.isNotEmpty(teachers)) {
                vo.setTeacherName(teachers.stream()
                        .map(UserDTO::getName).collect(Collectors.joining("/")));
            }
        }
        // 5.查询章节信息
        List<CataSimpleInfoDTO> catas = catalogueClient.batchQueryCatalogue(
                List.of(question.getChapterId(), question.getSectionId()));
        Map<Long, String> cataMap = new HashMap<>(catas.size());
        if (CollUtils.isNotEmpty(catas)) {
            cataMap = catas.stream()
                    .collect(Collectors.toMap(CataSimpleInfoDTO::getId, CataSimpleInfoDTO::getName));
        }
        vo.setChapterName(cataMap.getOrDefault(question.getChapterId(), ""));
        vo.setSectionName(cataMap.getOrDefault(question.getSectionId(), ""));
        // 6.封装VO
        return vo;
    }

    /**
     * 管理端隐藏或显示问题
     *
     * @param id
     * @param hidden
     */
    @Override
    public void hiddenQuestion(Long id, Boolean hidden) {
        // 1.更新问题
        InteractionQuestion question = new InteractionQuestion();
        question.setId(id);
        question.setHidden(hidden);
        updateById(question);
    }
}




